package cn.stylefeng.guns.core.util;

import cn.stylefeng.guns.base.shiro.ShiroUser;
import cn.stylefeng.guns.core.constant.JwtConstants;
import cn.stylefeng.guns.sys.core.shiro.ShiroKit;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.datascope.DataScope;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

@Component
public class UserUtil {

    @Autowired
    UserService userService;

    public static UserUtil userUtil;
    @PostConstruct
    public void init() {
        userUtil = this;
    }

    /**
     * 获取用户名从token中
     */
    public static User getUserFromToken(HttpServletRequest request) {

        final String requestHeader = request.getHeader(JwtConstants.API_HEADER);
        User result = null;
        if (requestHeader!=null){
            String userId = JwtTokenUtil.getUsernameFromToken(requestHeader);
            User user =  userUtil.userService.getByUserId(userId);
            result = user;
        }else {

            ShiroUser shiroUser = ShiroKit.getUser();
            if (shiroUser!=null) {
                result = userUtil.userService.getByUserId(shiroUser.getId().toString());
            }

        }
        return result;
    }

    /**
     * 获取用户名从token中
     */
    public static String getNameAccountFromToken(HttpServletRequest request) {

        final String requestHeader = request.getHeader(JwtConstants.API_HEADER);
        String result = null;
        if (requestHeader!=null){
            String userId = JwtTokenUtil.getUsernameFromToken(requestHeader);
            User user =  userUtil.userService.getByUserId(userId);
            String userName = user.getName();
            String account = user.getAccount();
            result = account + "-" + userName;
        }
        return result;
    }

    /**
     * 获取用户名从token中
     */
    public static String getUserIdFromToken(HttpServletRequest request) {

        final String requestHeader = request.getHeader(JwtConstants.API_HEADER);
        String result = null;
        if (requestHeader!=null){
            String userId = JwtTokenUtil.getUsernameFromToken(requestHeader);
            result = userId;
        }
        return result;
    }
}
